import { createAsyncThunk } from '@reduxjs/toolkit';
import { setLoading, setError, setAccounts } from '../reducers/accountReducer';
import api from '../services/api';

export const fetchAccounts = createAsyncThunk(
  'account/fetchAccounts',
  async (_, { dispatch }) => {
    dispatch(setLoading(true));
    try {
      const response = await api.fetchAccounts();
      dispatch(setAccounts(response.data.accounts));
    } catch (error) {
      const errorMessage = api.isAxiosError(error) && error.response 
        ? error.response.data.message || '发生错误' 
        : '发生错误'; // 提供更具体的错误信息
      dispatch(setError(errorMessage));
    } finally {
      dispatch(setLoading(false));
    }
  }
);
